jQuery(function ($) {
  var processFile = "assets/inc/ajax.inc.php";

  var fx = {
    initModal: function () {
      if ($(".modal-window").length == 0) {
        let modalDiv = $("<div></div>");
        return modalDiv.hide().addClass("modal-window").appendTo("body");
      } else {
        return $(".modal-window");
      }
    },
    //淡出
    boxout: function (event) {
      if (event != undefined) {
        event.preventDefault();
      }

      $("a").removeClass("active");

      $(".modal-window,.modal-overlay").fadeOut("slow", function () {
        $(this).remove();
      });
    },
    boxin: function (data, modal) {
      $("<div></div>")
        .hide()
        .addClass("modal-overlay")
        .click(function (event) {
          fx.boxout(event);
        })
        .appendTo("body");

      modal.hide().append(data).appendTo("body");

      $(".modal-window,.modal-overlay").fadeIn("slow");
    },
    addevent: function (data, formData) {
      var entry = fx.deserialize(formData),
        cal = new Date(NaN),
        event = new Date(NaN),
        cdata = $("h2").attr("id").split("-"),
        date = entry.event_start.split(" ")[0],
        edata = date.split("-");

      cal.setFullYear(cdata[1], cdata[2], 1);

      event.setFullYear(edata[0], edata[1], edata[2]);

      event.setMinutes(event.getTimezoneOffset());

      if (
        cal.getFullYear() == event.getFullYear() &&
        cal.getMonth() == event.getMonth()
      ) {
        var day = String(event.getDate());

        day = day.length == 1 ? "0" + day : day;

        $("<a></a>")
          .hide()
          .attr("href", "view.php?event_id=" + data)
          .text(entry.event_title)
          .insertAfter($("strong:contains(" + day + ")"))
          .delay(1000)
          .fadeIn("slow");
      }
    },
    deserialize: function (str) {
      var data = str.split("&"),
        pairs = [],
        entry = {},
        key,
        val;

      for (x in data) {
        pairs = data[x].split("=");

        key = pairs[0];
        val = pairs[1];

        entry[key] = fx.urldecode(val);
      }

      return entry;
    },
    urldecode: function (str) {
      var converted = str.replace(/\+/g, "  ");
      return decodeURIComponent(converted);
    },
    removeevent: function () {
      $(".active").fadeOut("slow", function () {
        $(this).remove();
      });
    },
  };

  $("li>a").on("click", function (event) {
    event.preventDefault();
    $(this).addClass("active");

    var data = $(this)
      .attr("href")
      .replace(/.+?\?(.*)$/, "$1");

    modal = fx.initModal();
    //删除按钮
    $("<a></a>")
      .attr("href", "#")
      .addClass("modal-close-btn")
      .html("&times;")
      .click(function (event) {
        // event.preventDefault();

        // $(".modal-window").remove();
        fx.boxout(event);
      })
      .appendTo(modal);

    $.ajax({
      type: "POST",
      url: processFile,
      data: "action=event_view&" + data,
      success: function (data) {
        fx.boxin(data, modal);
      },
      error: function (msg) {
        modal.append(msg);
      },
    });
  });
  //ajax 无法获取dom的问题
  $(document).on("click", ".admin-options form,.admin", function (event) {
    event.preventDefault();

    // var action = "edit_event";
    var action = $(event.target).attr("name") || "edit_event";

    id = $(event.target).siblings("input[name=event_id]").val();

    id = id != undefined ? "&event_id=" + id : "";

    // console.log("Add a New Event button clicked!");

    $.ajax({
      type: "POST",
      url: processFile,
      data: "action=" + action + id,
      success: function (data) {
        var form = $(data).hide();
        modal = fx
          .initModal()
          .children(":not(.modal-close-btn)")
          .remove()
          .end();

        fx.boxin(null, modal);

        form.appendTo(modal).addClass("edit-form").fadeIn("slow");
      },
      error: function (msg) {
        alert(msg);
      },
    });
  });

  $(document).on("click", ".edit-form a:contains(cancel)", function (event) {
    event.preventDefault();
    fx.boxout(event);
    return false;
  });

  $(document).on("click", ".edit-form input[type=submit]", function (event) {
    event.preventDefault();

    var formData = $(this).parents("form").serialize(),
      submitVal = $(this).val(),
      remove = false;

    if ($(this).attr("name") == "confirm_delete") {
      formData += "&action=confirm_delete" + "&confirm_delete=" + submitVal;

      if (submitVal == "Yes, Delete It") {
        remove = true;
      }
    }

    $.ajax({
      type: "POST",
      url: processFile,
      data: formData,
      success: function (data) {
        console.log("data", data);

        if (remove === true) {
          fx.removeevent();
        }

        fx.boxout();

        if (
          $("[name=event_id]").val() &&
          $("[name=event_id]").val().length == 0 &&
          remove === false
        ) {
          fx.addevent(data, formData);
        }

        //刷新一下页面
        setTimeout(function () {
          window.location.reload();
        }, 1000);
      },
      error: function (msg) {
        alert(msg);
      },
    });
    console.log("Form submission triggered!");
  });
});
